# Create your views here.
#coding:utf-8
from  django.conf import settings
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import messages
from wall.models import *
from bookwall.models import *
from models import *
from forms import *
from PIL import Image
from doubanbook import DBbook
import time
import re

def new_book(request):
    flag, pressdate_flag = False,False
    db,book_session,isbn_session = None,None,None
    try:
        db = request.session['dbbook']
        book_session = request.session['book']
        isbn_session = request.session['isbn']
    except:
        pass
    form = None
    if db:
        flag = True
        request.session['test'] = db
        form = BookForm(initial = {'bookname1' : db.title,'bookname2':db.subtitle,
            'isbn':db.isbn,'author1':db.author1,'author2':db.author2,
            'press':db.publish,'pressdate1':db.publish_time,
            'price':db.price})
    elif isbn_session: 
        form = BookForm(initial = {'isbn' : isbn_session}) 
    elif book_session:
        flag = True
        form = BookForm(initial = {'bookname1' : book_session.name,'bookname2' : book_session.second,
                'isbn' : book_session.isbn,'author1' : book_session.author1,'press' : book_session.publisher,
                'pressdate1' : book_session.publish_time,'price' : book_session.price})
    else:
        return HttpResponseRedirect(reverse('new_thing'))


    if request.method == "POST":
        print "post"
        copy = request.POST.copy()
        if db:
            copy['isbn'] = db.isbn
        elif book_session:
            copy['isbn'] = book_session.isbn
        else:
            copy['isbn'] = isbn_session
        print copy.keys()
        if flag:
            if db:
                copy['pressdate1'] = db.publish_time
            else:
                copy['pressdate1'] = book_session.publish_time 
        if copy['pressdate_month'] == "0":
            copy['pressdate_month'] = "1"

        if copy['pressdate_day'] == "0":
            copy['pressdate_day'] = "1"

        if copy['pressdate_year'] == "0":
            pressdate_flag = True
            copy['pressdate_year'] = "2012"
        form = BookForm(copy)

        if form.is_valid():
            print "valid"
            isbn = form.cleaned_data['isbn']
            detailnote = form.cleaned_data['detailnote']
            tag = form.cleaned_data['tag']
            tags = re.split(r'\s+',tag)
            tagModel = None
            book = None
            if flag:
                try:
                    book = BookWall.objects.get(isbn = isbn)
                except:
                    book = BookWall.objects.create(isbn = isbn,name = db.title,second = db.subtitle,
                            doubanlink = db.url,imglink_douban = db.img,content = db.summary,publisher = db.publish,
                            publish_time = db.publish_time,price = db.price,author1 = db.author1,user = request.user)
                    book.save()
                for t in tags:
                    try:
                        tagModel = Tag.objects.get(name = t)
                    except:
                        tagModel = Tag.objects.create(name = t)
                        tagModel.save()

                    try:
                        booktag = BookTag.objects.get(tag = tagModel,book = book)
                    except:
                        booktag = BookTag.objects.create(tag = tagModel,book = book)
                        booktag.save()
                wallkind = WallKind.objects.get(pk = 1)
                wall = WallList.objects.create(comments_num = 0,wallkind = wallkind,user = request.user)
                wall.title = db.title
                wall.content = detailnote
                wall.save()

                bookexchangeList = BookExchangeList.objects.create(wall = wall,book = book)
                bookexchangeList.save()

                return HttpResponseRedirect(reverse('wall_info',args = (wall.id,)))

            else:
                pressdate = pressdate_flag and "不详" or form.cleaned_data['pressdate']
                bookname1 = form.cleaned_data['bookname1'] 
                bookname2 = form.cleaned_data['bookname2']
                author = form.cleaned_data['author1']
                if form.cleaned_data['author2']:
                    author = author + "/" + form.cleaned_data['author2']
                press = form.cleaned_data['press']
                price = form.cleaned_data['price']
                book = BookWall.objects.create(isbn = isbn,name = bookname1, second = bookname2,
                        publisher = press,publish_time = pressdate,author1 = author,user = request.user)
                if price:
                    book.price = price
                book.save()

                for t in tags:
                    try:
                        tagModel = Tag.objects.get(name = t)
                    except:
                        tagModel = Tag.objects.create(name = t)
                        tagModel.save()

                    try:
                        booktag = BookTag.objects.get(tag = tagModel,book = book)
                    except:
                        booktag = BookTag.objects.create(tag = tagModel,book = book)
                        booktag.save()
                wallkind = WallKind.objects.get(pk = 1)
                wall = WallList.objects.create(comments_num = 0,wallkind = wallkind,user = request.user)
                wall.title = bookname1
                wall.content = detailnote
                wall.save()
                bookexchangeList = BookExchangeList.objects.create(wall = wall,book = book)
                bookexchangeList.save()
                return HttpResponseRedirect(reverse('wallinfo',args = (wall.id,)))
    return render_to_response("newbook2.html",{'form':form,"tag":flag},RequestContext(request))
